#include <stdio.h>

int htoi(char hex[]);
int hexWrite(FILE *out_fp);

int main(int argc, const char **argv)
{
    if(argc != 2)
    {
        fprintf(stderr, "Usage: %s [file]\n", *argv);
        return -1;
    }

    FILE *fp = fopen(argv[1], "w");
    if(fp)
        return hexWrite(fp);

    fprintf(stderr, "Failed open \"%s\"\n", argv[1]);
    return -1;
}

int hexWrite(FILE *out_fp)
{
    char i = 0;
    char hex[2];
    int in, out;
    while((in = fgetc(stdin)) != 'S')
        if(in == EOF)
            return -1;
    while(1)
    {
        in = fgetc(stdin);
        if(in != EOF)
        {
            if(in == ' ' || in == '\n')
                continue;
            if(i)
            {
                hex[i] = in;
                if((out = htoi(hex)) == -1)
                    return 1;
                fputc(out, out_fp);
                i = 0;
            } else {
                hex[i] = in;
                i = 1;
            }
        } else
            return -1;
    }
}

int htoi(char hex[])
{
    char s = 0;
    char mode = 0;
    int result = 0;
    char a = 0x57;
loop:
    if(hex[s] >= '0' && hex[s] <= '9')
        goto atoi;
    else if(hex[s] >= 'a' && hex[s] <= 'f')
        goto alpha;
    else if(hex[s] >= 'A' && hex[s] <= 'F')
    {
        mode = 1;
        goto alpha;
    } else
        return -1;
atoi:
    if(!s)
    {
        result = (hex[s] - 0x30) * 0x10;
        s++;
        goto loop;
    }
    result += hex[s] - 0x30;
    return result;
alpha:
    if(mode)
        a = 0x37;
    if(!s)
    {
        result = (hex[s] - a) * 0x10;
        s++;
        goto loop;
    }
    result += hex[s] - a;
    return result;
}
